package com.leyou.mq;

import com.leyou.common.constants.MQConstants;
import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.utils.SmsUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @author 虎哥
 */
@Component
public class MessageListener {

    @Autowired
    private SmsUtils smsUtils;

    /**
     * 监听短信验证码的消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.Queue.SMS_VERIFY_CODE_QUEUE, durable = "true"),
            exchange = @Exchange(name = MQConstants.Exchange.SMS_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKey.VERIFY_CODE_KEY
    ))
    public void listenSendVerifyCode(Map<String, String> msg) {
        if (CollectionUtils.isEmpty(msg)) {
            // 如果消息为空，说明是垃圾消息，直接丢弃
            return;
        }
        // 获取手机号
        String phone = msg.get("phone");
        // 校验phone
        if (!RegexUtils.isPhone(phone)) {
            // 说明是垃圾消息，直接丢弃
            return;
        }
        // 获取code
        String code = msg.get("code");
        // 校验code
        if (!RegexUtils.isCodeValid(code)) {
            // 说明是垃圾消息，直接丢弃
            return;
        }
        try {
            smsUtils.sendVerifyCode(phone, code);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
